package Controller

import (
	"back_go/Dto"
	"back_go/Response"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gopkg.in/ini.v1"
	"io"
	"math"
	"net/http"
	"strconv"
	"time"
)

type BlockInfo struct {
	BlockHash   string `json:"blockHash"`
	BlockNumber uint64 `json:"blockNumber"`
}

// GetLastBlockInfo 获取最后一个区块的信息
func GetLastBlockInfo(c *gin.Context) {
	// 加载配置文件
	cfg, err := ini.Load("./Config/config.ini")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "加载配置文件失败: " + err.Error()})
		return
	}
	remoteURL := cfg.Section("blockchain").Key("url").String() + "/GetLastBlockInfo"
	// 发送 HTTP GET 请求
	resp, err := http.Get(remoteURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to call remote service: " + err.Error(),
		})
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to read response body: " + err.Error(),
		})
		return
	}

	// 解析响应体
	var remoteResp BlockInfo
	err = json.Unmarshal(body, &remoteResp)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to parse response: " + err.Error(),
		})
		return
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		c.JSON(resp.StatusCode, gin.H{
			"error": fmt.Sprintf("Remote service returned status code %d: %s", resp.StatusCode, string(body)),
		})
		return
	}

	// 返回远程服务的响应
	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Msg:       nil,
		Data:      remoteResp,
		Version:   "v1.0",
		Timestamp: time.Now().Unix(),
		Sign:      nil,
		Success:   true,
		Fail:      false,
	})
}

// GetAllAssetByBlock 获取资产
func GetAllAssetByBlock(c *gin.Context) {
	var orderAssetDto *[]Dto.OrderAssetDto
	// 加载配置文件
	cfg, err := ini.Load("./Config/config.ini")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "加载配置文件失败: " + err.Error()})
		return
	}
	remoteURL := cfg.Section("blockchain").Key("url").String() + "/GetAllAsset"
	// 发送 HTTP GET 请求
	resp, err := http.Get(remoteURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to call remote service: " + err.Error(),
		})
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to read response body: " + err.Error(),
		})
		return
	}

	// 解析响应体

	err = json.Unmarshal(body, &orderAssetDto)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to parse response: " + err.Error(),
		})
		return
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		c.JSON(resp.StatusCode, gin.H{
			"error": fmt.Sprintf("Remote service returned status code %d: %s", resp.StatusCode, string(body)),
		})
		return
	}

	// 返回远程服务的响应

	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      orderAssetDto,
		Msg:       nil,
		Success:   true,
		Timestamp: time.Now().Unix(),
	})
}

// GetAssetNumber 获取链上资产数量
func GetAssetNumber(c *gin.Context) {
	var res *int
	// 加载配置文件
	cfg, err := ini.Load("./Config/config.ini")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "加载配置文件失败: " + err.Error()})
		return
	}
	remoteURL := cfg.Section("blockchain").Key("url").String() + "/GetAssetNumber"
	// 发送 HTTP GET 请求
	resp, err := http.Get(remoteURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to call remote service: " + err.Error(),
		})
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to read response body: " + err.Error(),
		})
		return
	}

	// 解析响应体

	err = json.Unmarshal(body, &res)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to parse response: " + err.Error(),
		})
		return
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		c.JSON(resp.StatusCode, gin.H{
			"error": fmt.Sprintf("Remote service returned status code %d: %s", resp.StatusCode, string(body)),
		})
		return
	}

	// 返回远程服务的响应

	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      res,
		Msg:       nil,
		Success:   true,
		Timestamp: time.Now().Unix(),
	})
}

type AllAssetsWithPagination struct {
	OrderAssets []Dto.OrderAssetDto `json:"data"`
	Current     string              `json:"current"`
}

// GetAllAssetsWithPaginationRemote 向远程服务发送请求获取分页资产信息
func GetAllAssetsWithPaginationRemote(c *gin.Context) {
	// 获取分页参数
	pageSizeStr := c.Query("pageSize")
	currentStr := c.Query("current")
	orderNumber := c.Query("orderNumber")
	fmt.Println("pageSizeStr:", pageSizeStr, "current:", currentStr, "orderNumber:", orderNumber)
	// 转换 pageSize 参数
	pageSize, err := strconv.ParseInt(pageSizeStr, 10, 32)
	if err != nil || pageSize < 1 {
		pageSize = 10 // 默认每页 10 条
	}

	// 加载配置文件
	cfg, err := ini.Load("./Config/config.ini")
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "加载配置文件失败: " + err.Error()})
		return
	}
	remoteURL := cfg.Section("blockchain").Key("url").String() + "/GetAllAssetsWithPagination"
	// 构建请求 URL
	queryParams := fmt.Sprintf("?pageSize=%d&currentStr=%s&orderNumber=%s", pageSize, currentStr, orderNumber)
	fullURL := remoteURL + queryParams
	fmt.Println("请求区块链信息    发送的url" + fullURL)
	// 发送 HTTP GET 请求
	resp, err := http.Get(fullURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to call remote service: " + err.Error(),
		})
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to read response body: " + err.Error(),
		})
		return
	}

	// 解析响应体
	var res AllAssetsWithPagination
	err = json.Unmarshal(body, &res)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to parse response: " + err.Error(),
		})
		return
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		c.JSON(resp.StatusCode, gin.H{
			"error": fmt.Sprintf("Remote service returned status code %d: %s", resp.StatusCode, string(body)),
		})
		return
	}
	//---------------------------------------------------
	var total *int
	// 加载配置文件

	remoteURL = cfg.Section("blockchain").Key("url").String() + "/GetAssetNumber"
	queryParams = fmt.Sprintf("?orderNumber=%s", orderNumber)
	remoteURL = remoteURL + queryParams
	// 发送 HTTP GET 请求
	resp, err = http.Get(remoteURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to call remote service: " + err.Error(),
		})
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err = io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to read response body: " + err.Error(),
		})
		return
	}

	// 解析响应体

	err = json.Unmarshal(body, &total)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "Failed to parse response: " + err.Error(),
		})
		return
	}

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		c.JSON(resp.StatusCode, gin.H{
			"error": fmt.Sprintf("Remote service returned status code %d: %s", resp.StatusCode, string(body)),
		})
		return
	}
	fmt.Println("currentStr", currentStr)
	current, err := strconv.ParseInt(currentStr, 10, 64)
	if total == nil {
		*total = 0
	}
	// 返回远程服务的响应
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: PageParam1[Dto.OrderAssetDto]{
			Current: current,
			Records: res.OrderAssets,
			Total:   total,
			Pages:   int(math.Ceil(float64(*total) / float64(pageSize))),
			Size:    pageSize,
		},
		Msg:       nil,
		Success:   true,
		Timestamp: time.Now().Unix(),
	})
}
